<template>
    <div class="l_list">
        <div class="list_t">
            <span class="fl list_or">
                <a href="#" class="now" @click.prevent="changeDefaultSort()">默认</a>
                <a href="#" @click.prevent="changeSalesSort()">
                    <span class="fl">{{ salesSort === null ? '销量' : salesSort === true ? '销量↑' : '销量↓' }}</span>
                </a>
                <a href="#" @click.prevent="changePriceSort()">
                    <span class="fl">{{ priceSort === null ? '价格' : priceSort === true ? '价格↑' : '价格↓' }}</span>
                </a>
            </span>
            <span class="fr">共发现{{ pageInfo.total }}件</span>
        </div>
        <div class="list_c" v-if="pageInfo.total === 0">
            <h1 style="color:#e74c3c ;">您当前搜索的商品不翼而飞了！</h1>
        </div>
        <div class="list_c">
            <ul class="cate_list">
                <li v-for="product in productList" :key="product.id">
                    <div class="img"><a href="#" @click.prevent="toProductDetail(product.id)"><img
                                :src="'http://192.168.144.183:9090/easybuyImages/' + product.fileName" width="210"
                                height="185" /></a></div>
                    <div class="price">
                        <font>￥<span>{{ product.price }}</span></font> &nbsp;
                    </div>
                    <div class="name"><a href="#" v-html="product.name"></a></div>
                    <div class="carbg">
                        <a href="#" class="ss" :class="{ collect: false }"
                            @click.prevent="checkIsCollect(product)">收藏</a>
                        <a href="#" class="j_car" @click.prevent="getBuyCar(product)">加入购物车</a>
                    </div>
                </li>
            </ul>
            <p class="pagination" v-if="pageInfo.total !== 0">
                <span class="left-buttons">
                    <button @click="nextPage('home')" :disabled="pageInfo.pageNum === 1">首页</button>&nbsp;&nbsp;
                    <button @click="nextPage('pre')" :disabled="pageInfo.pageNum === 1">上一页</button>&nbsp;&nbsp;

                    <span v-for="page in visiblePages" :key="page">
                        <button @click="getProductList(page, 8)" :class="{ active: page === pageInfo.pageNum }">
                            {{ page }}
                        </button>&nbsp;
                    </span>&nbsp;

                    <button @click="nextPage('next')" :disabled="pageInfo.pageNum === pageInfo.pages">下一页</button>&nbsp;
                    <button @click="nextPage('end')" :disabled="pageInfo.pageNum === pageInfo.pages">尾页</button>&nbsp;
                </span>
            </p>

            <!-- <div class="pages">
                <a href="#" class="p_pre">上一页</a><a href="#" class="cur">1</a><a href="#">2</a><a href="#">3</a>...<a
                    href="#">20</a><a href="#" class="p_pre">下一页</a>
            </div> -->
        </div>
    </div>
</template>

<script>
export default {
    name: 'ProductShow',
    data() {
        return {
            // 分页信息
            pageInfo: {},
            productList: [],
            priceSort: null,
            salesSort: null,
            userId: '',
            buyCar: null,
            isCheck: false
        }
    },
    computed: {
        visiblePages() {
            const total = this.pageInfo.pages;
            const current = this.pageInfo.pageNum;
            const range = 2; // 当前页左右各显示2页
            let start = Math.max(1, current - range);
            let end = Math.min(total, current + range);
            const pages = [];
            for (let i = start; i <= end; i++) {
                pages.push(i);
            }
            return pages;
        }
    },
    methods: {
        toProductDetail(id) {
            // console.log("商品Id为" + id)
            this.$router.push({ path: '/productDetail', query: { id: id } })
        },
        changeDefaultSort() {
            this.priceSort = null
            this.salesSort = null
            this.getProductList(1, 20)
        },
        changePriceSort() {
            this.priceSort = this.priceSort === null ? false : !this.priceSort
            this.salesSort = null
            this.getProductList(1, 20)
        },
        changeSalesSort() {
            this.salesSort = this.salesSort === null ? false : !this.salesSort
            this.priceSort = null
            this.getProductList(1, 20)
        },
        //获取产品列表数据
        getProductList(pageNum, pageSize) {
            const query = this.$route.query;
            const data = {
                pageNum: pageNum,
                pageSize: pageSize,
                name: query.product || '',
                categoryLevel1Id: query.categoryLevel1Id || '',
                categoryLevel2Id: query.categoryLevel2Id || '',
                categoryLevel3Id: query.categoryLevel3Id || '',
            }
            if (this.priceSort !== null) {
                data.priceSort = this.priceSort;
            }
            if (this.salesSort !== null) {
                data.salesSort = this.salesSort;
            }
            this.$axios({
                url: '/selectProductByPage',
                method: 'post',
                data: data,
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(rs => {
                //console.log("商品数据" + rs)
                this.pageInfo = rs.data.pageInfo
                this.productList = rs.data.pageInfo.list
            })
        }
        // 跳页
        , nextPage(rep) {
            let pageNum = 1;
            switch (rep) {
                case "next":
                    pageNum = this.pageInfo.nextPage === 0 ? this.pageInfo.pages : this.pageInfo.nextPage;
                    break;
                case "pre":
                    pageNum = this.pageInfo.prePage === 0 ? 1 : this.pageInfo.prePage;
                    break;
                case "end":
                    pageNum = this.pageInfo.pages;
                    break;
            }
            this.getProductList(pageNum, 20)
        },

        toAddCollect(product) {
            this.$axios({
                url: 'addCollect',
                method: 'post',
                data: { userId: this.userId, product: product },
                headers: { 'content-type': 'application/json' }
            }).then(rs => {
                if (rs.data.code == 5200 || rs.data.code == '5200') {
                    alert('添加成功！')

                } else {
                    alert('添加失败')
                }
            })
        },
        addToBuyCar(product) {

            if (this.buyCar == null || this.buyCar == '') {
                this.$axios({
                    url: 'addBuyCar',
                    method: 'post',
                    data: {
                        userId: this.userId,
                        number: 1,
                        pid: product.id
                    },
                    headers: {
                        'content-type': 'application/json'
                    }
                }).then(rs => {
                    if (rs.data.code == 5200 || rs.data.code == '5200') {
                        alert('添加成功！')
                    } else {
                        alert('添加失败！')
                    }
                })
            } else {
                console.log(this.buyCar.product.stock)
                if (this.buyCar.number + 1 > product.stock) {
                    alert('库存不足！')
                    return
                }
                this.$axios({
                    url: 'updateBuyCar',
                    method: 'post',
                    data: {
                        id: this.buyCar.id,
                        number: this.buyCar.number + 1
                    },
                    headers: { 'content-type': 'application/json' }
                }).then(rs => {
                    if (rs.data.code == 5200 || rs.data.code == '5200') {
                        alert('添加成功！')
                    } else {
                        alert('添加失败！')
                    }
                })
            }

        },
        getBuyCar(product) {
            this.$axios({
                url: 'addBuyCarNum',
                method: 'get',
                params: { userId: this.userId, pid: product.id }
            }).then(rs => {
                if (rs.data.code) {
                    if (rs.data.code == 5200 || rs.data.code == '5200') {
                        this.buyCar = rs.data.buyCar
                        this.addToBuyCar(product)
                    } else {
                        alert('添加失败！')
                    }
                }
            })
        },
        checkIsCollect(product) {
            this.$axios({
                url: 'checkIsCollect',
                params: { pid: product.id, userId: this.userId }
            }).then(rs => {
                if (rs.data.code) {
                    if (rs.data.code == 5200 || rs.data.code == '5200') {
                        this.toAddCollect(product)
                        this.isCheck = false
                    } else {
                        alert('该商品已经被收藏！')
                        this.isCheck = true
                    }
                }
            })
        },
        // addIsCheckClass(product){
        //     this.checkIsCollect(product)
        //     return this.isCheck
        // }

    },
    mounted() {
        this.userId = window.sessionStorage.getItem('userId')
        this.getProductList(1, 20)
    }, watch: {
        '$route.query': {
            immediate: true,
            handler(newQuery) {
                this.name = newQuery.product || '';
                this.getProductList(1, 20);
            }
        }
    }
}
</script>

<style scoped>
.collect {
    color: #888888;
    background: url(../assets/images/heart_h.png) no-repeat 10px center !important;
    width: 40% !important;
}
</style>